<template>
  <el-row>
    <div class="block">
      <el-date-picker v-model="value2" type="datetimerange" :shortcuts="shortcuts" range-separator="To" start-placeholder="起始日期" end-placeholder="结束日期" />
    </div>
    <div class="block">
      <el-select v-model="value3" placeholder="选择区域" style="width: 240px">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </div>

  </el-row>
  <div>
    <el-card><div ref="chart" style="height: 300px; width: 1300px"></div></el-card>
    <el-card><div ref="chart2" style="height: 300px; width: 1300px"></div></el-card>
    <el-card>
      <el-button @click="exportToExcel">导出为 Excel</el-button>
      <el-table :data="pagedTableData1" border style="width: 90%">
    <el-table-column prop="starttime" label="时间" width="180" :formatter="formatTime.formatTime"></el-table-column>
    <el-table-column prop="assetnum" label="工位ID" width="150"></el-table-column>
    <el-table-column prop="toolnumber" label="刀具号" width="100"></el-table-column>
    <el-table-column prop="formattedDuration" label="换刀耗时/s" width="125"></el-table-column>
    <el-table-column prop="standardDuration" label="换刀耗时标准/s" width="125"></el-table-column>
    <el-table-column prop="old_maxlife" label="预设寿命/件" width="125"></el-table-column>
    <el-table-column prop="old_actuallife" label="下刀寿命/件" width="125"></el-table-column>
    <el-table-column prop="lifespansRatio" label="寿命符合率" width="125"></el-table-column>
    <el-table-column prop="isAbnormalChange" label="是否异常" width="125"></el-table-column>
  </el-table>
  <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalItems"
      />
    </el-card>
    <el-card>
      <h3>换刀耗时异常待确认（换刀耗时>20min）</h3>
      <el-table :data="tableData3" border style="width: 90%">
    <el-table-column prop="starttime" label="时间" width="180" :formatter="formatTime.formatTime"></el-table-column>
    <el-table-column prop="assetnum" label="工位ID" width="150"></el-table-column>
    <el-table-column prop="toolnumber" label="刀具号" width="100"></el-table-column>
    <el-table-column prop="formattedDuration" label="换刀耗时/s" width="125"></el-table-column>
    <el-table-column prop="standardDuration" label="换刀耗时标准/s" width="125"></el-table-column>
    <el-table-column prop="old_maxlife" label="预设寿命/件" width="125"></el-table-column>
    <el-table-column prop="old_actuallife" label="下刀寿命/件" width="125"></el-table-column>
    <el-table-column prop="lifespansRatio" label="寿命符合率" width="125"></el-table-column>
    <el-table-column prop="isAbnormalChange" label="是否异常" width="125"></el-table-column>
  </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, toRef, toRefs, computed } from "vue";
import * as echarts from "echarts"; 
import axios from "axios";
import XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import { convertCompilerOptionsFromJson } from "typescript";

const value2 = ref([]);

const shortcuts = [
  {
    text: "近1周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 7);
      return [start, end];
    },
  },
  {
    text: "近1月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 1);
      return [start, end];
    },
  },
];
const chart = ref(); //创建dom引用
const chart2 = ref();
const chartInstance2 = ref(null);
const series_data2 = ref();
const series_data = ref();
const series_data1 = ref();
const tableData = ref([]);
const tableData3 = ref([]);
const currentPage = ref(1);
const pageSize = ref(5);
const totalItems = ref(0);
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  updatePagedData();
};
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  updatePagedData();
};
const updatePagedData = () => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  pagedTableData1.value = tableData.value.slice(startIndex, endIndex);
  console.log('ble',pagedTableData1.value)
};

const pagedTableData1 = ref([]);

const formatTime = {
  formatTime(row, column) {
    if (row.starttime) {
      return row.starttime.split('.')[0];
    }
    return '';
  }
};

const initChart = async () => {
  if (chart.value == null) {
    return;
  }

  echarts.dispose(chart.value);
  var myChart = echarts.init(chart.value);
  myChart.setOption({});
  let option = {
    tooltip: {
      trigger: "axis",
      formatter: function (params) {
        var result = "";
        for (var i = 0; i < params.length; i++) {
          var param = params[i];
          if (i === 0) {
            result += param.name + "<br/>";
          }
          result += param.seriesName + ": " + param.value + "<br/>";
        }
        return result;
      },
    },
    legend: {
      data: ["总换刀耗时","异常换刀耗时"],
      orient: "horizontal", 
      left: "left", 
      top: "top",
      itemGap: 10, 
    },
    toolbox: {
      show: true,
      feature: {
        mark: { show: true },
        dataView: { show: true, readOnly: false },
        magicType: { show: true, type: ["line", "bar"] },
        restore: { show: true },
        saveAsImage: { show: true },
      },
    },

    title: {
      text: `${value3.value} 换刀耗时分析`,
      left: "center",
      subtext: "s",
      textStyle: {
        color: "black", 
      },
      subtextStyle: {
        fontWeight: "bold",
      },
    },
    xAxis: {
      type: "category",
      data: series_data1.value,
      axisLabel: {
            rotate: 45 
          }
    },
    dataZoom: [
      {
        type: "slider", 
        start: 0, 
        end: 100, 
      },
      {
        type: "inside", 
        start: 90, 
        end: 100, 
      },
    ],
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "总换刀耗时",
        data: series_data2.value,
        type: "bar",
        color: "#00FF00",
        label: {
          show: true, 
          position: 'top', 
          formatter: function (param) {
            return parseFloat(param.value).toFixed(2); 
          }, 
        },
      },
      {
        name: "异常换刀耗时",
        data: series_data.value,
        type: "bar",
        color: "ORANGE",
        label: {
          show: true, 
          position: 'top', 
          formatter: function (param) {
            return parseFloat(param.value).toFixed(2); 
          },
        },
      },
    ],
  };
  myChart.on('click', (params) => {
      console.log('Clicked:', params);
      const equipment_id = params.name; 
    useShowDataInHtmlForTable(equipment_id);
  });
  myChart.setOption(option);
};

const initChart2 = async (equipmentId) => {
  if (chartInstance2.value == null) {
    return;
  }

  echarts.dispose(chartInstance2.value);
  var myChart2 = echarts.init(chartInstance2.value);
  myChart2.setOption({});

  let option2 = {
    tooltip: {
      trigger: "axis",
      formatter: function (params) {
        var result = "";
        for (var i = 0; i < params.length; i++) {
          var param = params[i];
          if (i === 0) {
            result += param.name + "<br/>";
          }
          result += param.seriesName + ": " + param.value + "<br/>";
        }
        return result;
      },
    },
    legend: {
      data: ["换刀耗时"],
      orient: "horizontal", 
      left: "left", 
      top: "top", 
      itemGap: 10, 
    },
    title: {
      text: `${equipmentId} 换刀情况`,
      left: "center",
      textStyle: {
        color: "black", 
      },
      subtextStyle: {
        fontWeight: "bold",
      },
    },
    xAxis: {
      type: "category",
      data: series_data3.value,
    },
    dataZoom: [
      {
        type: "slider", 
        start: 0, 
        end: 100, 
      },
      {
        type: "inside", 
        start: 90, 
        end: 100, 
      },
    ],
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "换刀耗时",
        data: series_data5.value,
        type: "bar",
        color: "#00ff00",
        label: {
          show: true, 
          position: 'top', 
          formatter: function (param) {
            return parseFloat(param.value).toFixed(2); 
          }, 
        },
      },
    ],
  };
  myChart2.setOption(option2);
};

onMounted(() => {
  const oneWeekAgo = new Date(Date.now() - 4 * 24 * 60 * 60 * 1000);
  const today = new Date();
  value2.value = [oneWeekAgo, today];
  use_show_data_in_html2();
  chartInstance2.value = chart2.value; 
  initChart2();
  useShowDataInHtmlForTable("CBM1OP10B");
  updatePagedData();
});

const value3 = ref("CB1");
const options = [
  { value: "CB1", label: "缸体M1" },
  { value: "CB2", label: "缸体M2" },
  { value: "CH1", label: "缸盖M1" },
  { value: "CH2", label: "缸盖M2" },
  { value: "CS", label: "曲轴M1" },
];

function formatDate(d: string) {
  var date = new Date(d);
  var YY = date.getFullYear() + "-";
  var MM = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
  var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var hh = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  var mm = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
  var ss = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return YY + MM + DD + " " + hh + mm + ss;
}

var construct_url = "";
watch([toRef(value2), toRef(value3)], ([newDateRange, newValue3]) => {
  const start_time = formatDate(newDateRange[0]);
  const end_time = formatDate(newDateRange[1]);
  construct_url = "http://10.64.35.32:8000/postgresql_data_api/get_ToolChangTime_data/?" + "start_time=" + start_time?.toString() + "&end_time=" + end_time?.toString() + "&location=" + newValue3 +"&page_size=" + 100001;
  use_show_data_in_html2();
});

const series_data3 = ref();
const series_data4 = ref();
const series_data5 = ref();
const extractOpNumber = (str) => {
  const match = str.match(/OP(\d+)/);
  return match ? parseInt(match[1], 10) : null;
};

const filterUniqueDataByLifespansRatio = (data) => {
  const uniqueDataMap = {};

  data.forEach(item => {
    const datePart = new Date(item.starttime).toISOString().slice(0, 16); 
    const lifespansRatio = ((item.old_actuallife / item.old_maxlife) * 100).toFixed(2);
    const uniqueKey = `${item.assetnum}-${datePart}`;

    if (!uniqueDataMap[uniqueKey]) {
      uniqueDataMap[uniqueKey] = { ...item, lifespansRatio: parseFloat(lifespansRatio) };
    } else {
      const existingItem = uniqueDataMap[uniqueKey];
      const existingRatio = parseFloat(existingItem.lifespansRatio);
      const currentRatio = parseFloat(lifespansRatio);

      if (currentRatio > existingRatio || 
          (currentRatio === existingRatio && item.duration < existingItem.duration)) {
        uniqueDataMap[uniqueKey] = { ...item, lifespansRatio: parseFloat(lifespansRatio) };
      }
    }
  });

  return Object.values(uniqueDataMap);
};

const getFilteredData = async (data) => {
  const breakDataUrl = `http://10.64.35.32:8000/man_ana_sql_server/get_Schedule/?sub_area=CAC01`;
  const breakResponse = await axios.get(breakDataUrl);
  
  const allBreaks = breakResponse.data.flatMap(schedule => [
    { start: schedule.break_1_start, end: schedule.break_1_end },
    { start: schedule.break_2_start, end: schedule.break_2_end },
    { start: schedule.break_3_start, end: schedule.break_3_end },
    { start: schedule.break_4_start, end: schedule.break_4_end },
    { start: schedule.break_5_start, end: schedule.break_5_end }
  ]);

  console.log('allBreaks',allBreaks)
  function isDuringBreaks(starttime, breaks) {
    return breaks.some(breakPeriod => 
      new Date(starttime) >= new Date(breakPeriod.start) && 
      new Date(starttime) <= new Date(breakPeriod.end)
    );
  }

  const filteredData = data.filter(item => !isDuringBreaks(item.starttime, allBreaks));
  console.log('filteredData',filteredData)
  return filteredData;
};

const use_show_data_in_html2 = async () => {
  console.log(construct_url);
  const response = await axios.get(construct_url);
  const data = response.data;
  console.log(data);

  const filteredData = await getFilteredData(data);

  const uniqueFilteredData = filterUniqueDataByLifespansRatio(filteredData)
                             .filter(item => item.assetnum.includes('OP') && item.duration <= 1200)
                             .sort((a, b) => extractOpNumber(a.assetnum) - extractOpNumber(b.assetnum));

  series_data1.value = [];
  series_data2.value = [];
  series_data.value = [];

  const timeSumByEquipment = new Map();
  const abnormalTimeSumByEquipment = new Map();

  uniqueFilteredData.forEach(item => {
    const equipmentId = item.assetnum;
    const duringTime = item.duration;
    const maxLife = item.old_maxlife;
    const actualLife = item.old_actuallife;

    if (!timeSumByEquipment.has(equipmentId)) {
      timeSumByEquipment.set(equipmentId, { full: 0, abnormal: 0 });
    }

    timeSumByEquipment.get(equipmentId).full += duringTime;
    if (maxLife - actualLife > 10) {
      timeSumByEquipment.get(equipmentId).abnormal += duringTime;
    }
  });

  series_data1.value = Array.from(timeSumByEquipment.keys());
  series_data2.value = Array.from(timeSumByEquipment.values()).map(val => parseFloat(val.full.toFixed(2)));
  series_data.value = Array.from(timeSumByEquipment.values()).map(val => parseFloat(val.abnormal.toFixed(2)));

  initChart();
};

const useShowDataInHtmlForTable = async (equipmentId) => {
  try {
    const start_time = formatDate(value2.value[0]);
    const end_time = formatDate(value2.value[1]);

    const url = `http://10.64.35.32:8000/postgresql_data_api/get_ToolChangTime_data/?start_time=${start_time}&end_time=${end_time}&location=${value3.value}&assetnum=${equipmentId}&page_size=100001`;
    console.log(url);
    const response = await axios.get(url);
    const data = response.data;
    console.log(data);

    const filteredData = await getFilteredData(data);

    const uniqueDataMap = {};
    const uniqueDataMap3 = {};

    filteredData.forEach(item => {
  const datePart = new Date(item.starttime).toISOString().slice(0, 16); 
  const lifespansRatio = ((item.old_actuallife / item.old_maxlife) * 100).toFixed(2);

  const targetMap = item.duration <= 1200 ? uniqueDataMap : uniqueDataMap3;
  const existingItem = targetMap[datePart];
  
  if (!existingItem || parseFloat(lifespansRatio) > parseFloat(existingItem.lifespansRatio) || 
      (parseFloat(lifespansRatio) === parseFloat(existingItem.lifespansRatio) && item.duration < existingItem.duration)) {
    targetMap[datePart] = { ...item, lifespansRatio: parseFloat(lifespansRatio) };
  }
});

    const uniqueData = Object.values(uniqueDataMap);
    const uniqueData3 = Object.values(uniqueDataMap3);

    const formatData = (items) => items.map(item => {
      const isAbnormal = item.old_maxlife - item.old_actuallife <= 10 ? '否' : '是';
      return {
        ...item,
        formattedDuration: (item.duration).toFixed(2),
        standardDuration: 60,
        isAbnormalChange: isAbnormal,
        lifespansRatio: `${item.lifespansRatio}%`,
      };
    });

    tableData.value = formatData(uniqueData);
    totalItems.value = tableData.value.length;

    tableData3.value = formatData(uniqueData3);
    console.log('table1', tableData.value);
    console.log('table2', tableData3.value);
    series_data3.value = [];
    series_data5.value = [];

    // 更新图表数据
    tableData.value.forEach(item => {
      const { starttime, duration } = item;
      series_data3.value.push(starttime);
      series_data5.value.push(duration);
    });

    initChart2(equipmentId);
    updatePagedData();
  } catch (error) {
    console.error(error);
    ElMessage.error('加载数据失败。');
  }
};
const exportToExcel = () => {
  import('xlsx').then(XLSX => {
    const worksheet = XLSX.utils.json_to_sheet(tableData.value);
    const workbook = { Sheets: { data: worksheet }, SheetNames: ['data'] };
    const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    const start = formatDate(value2.value[0]);
    const end = formatDate(value2.value[1]);
    const region = value3.value.replace(/\s/g, ''); 
    const filename = `${start}_${end}_${region}_节拍统计.xlsx`;

    saveAs(new Blob([excelBuffer], { type: 'application/octet-stream' }), filename);
  });
};
</script>

<style scoped>
h3 {
  color: black;
}

.block {
  padding: 20px;
  text-align: center;
  flex: 1;
}
.block:last-child {
  border-right: none;
}
.block .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.el-select .el-scrollbar__wrap {
  max-height: 50px !important;
  overflow-y: auto !important;
}
</style>
